package com.flaremars.picker.activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.flaremars.picker.MainActivity;
import com.flaremars.picker.R;
import com.flaremars.picker.constants.ProjectConstants;
import com.flaremars.picker.entities.LeafCard;
import com.flaremars.picker.entities.LeafCardService;
import com.flaremars.picker.utils.http.newhttp.HttpHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WelcomeActivity extends AppCompatActivity {

    private ExecutorService singleThreadExecutor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                getBaseCards();
                getCollectedCards();
                singleThreadExecutor.shutdown();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                        WelcomeActivity.this.finish();
                    }
                });
            }
        });
    }

    private void getBaseCards() {
        SharedPreferences sharedPreferences = getSharedPreferences(ProjectConstants.SHARED_PREFERENCE_NAME,MODE_PRIVATE);
        int leafCardsVersion = sharedPreferences.getInt(ProjectConstants.PREFERENCE_LEAF_CARDS_VERSION,0);
        Map<String,String> params = new HashMap<>();
        params.put("version", String.valueOf(leafCardsVersion));
        try {
            String response = HttpHelper.INSTANCE.post(ProjectConstants.BASE_URL + "leafCards/getBase",params);
            Log.e("tag", response);
            JSONObject root = new JSONObject(response);
            int statusCode = root.getInt("statusCode");
            if (statusCode == ProjectConstants.STATUS_CODE_NEED_UPDATE_BASE_CARDS) {
                JSONObject data = root.getJSONObject("data");
                leafCardsVersion = data.getInt("leafCardsVersion");
                JSONArray objectArray = data.getJSONArray("objects");
                List<LeafCard> entities = new ArrayList<>(objectArray.length());
                for (int i = 0;i < objectArray.length();i++) {
                    JSONObject temp = objectArray.getJSONObject(i);
                    LeafCard tempEntity = new LeafCard();
                    fillEntity(tempEntity,temp);
                    entities.add(tempEntity);
                }
                sharedPreferences.edit().putBoolean(ProjectConstants.PREFERENCE_LEAF_CARDS_GOT_COLLECTED, false).apply();
                LeafCardService.INSTANCE.saveAll(entities,true);
            }

            sharedPreferences.edit().putInt(ProjectConstants.PREFERENCE_LEAF_CARDS_VERSION,leafCardsVersion).apply();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getCollectedCards() {
        SharedPreferences sharedPreferences = getSharedPreferences(ProjectConstants.SHARED_PREFERENCE_NAME,MODE_PRIVATE);
        boolean gotCollected = sharedPreferences.getBoolean(ProjectConstants.PREFERENCE_LEAF_CARDS_GOT_COLLECTED, false);
        if (!gotCollected) {
            Map<String,String> params = new HashMap<>();
            params.put("userId", String.valueOf(1));
            try {
                String response = HttpHelper.INSTANCE.post(ProjectConstants.BASE_URL + "leafCards/getCollected",params);
                Log.e("tag", response);
                JSONObject root = new JSONObject(response);
                int statusCode = root.getInt("statusCode");
                if (statusCode != ProjectConstants.STATUS_CODE_ERROR) {
                    JSONObject data = root.getJSONObject("data");
                    JSONArray objectArray = data.getJSONArray("objects");
                    List<LeafCard> entities = new ArrayList<>(objectArray.length());
                    for (int i = 0;i < objectArray.length();i++) {
                        JSONObject temp = objectArray.getJSONObject(i);
                        LeafCard tempEntity = new LeafCard();
                        fillEntity(tempEntity,temp);
                        entities.add(tempEntity);
                    }
                    LeafCardService.INSTANCE.saveAll(entities,false);
                    sharedPreferences.edit().putBoolean(ProjectConstants.PREFERENCE_LEAF_CARDS_GOT_COLLECTED, true).apply();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void fillEntity(LeafCard entity,JSONObject jsonObject) {
        try {
            entity.setLeafCardId(jsonObject.getString("leafCardId"));
            entity.setImageUrl(jsonObject.getString("imageUrl"));
            entity.setCollectedTime(new Date(jsonObject.getLong("collectedTime")));
            entity.setCollectedPlace(jsonObject.getString("collectedPlace"));
            entity.setCardName(jsonObject.getString("cardName"));
            entity.setCardIndex(jsonObject.getInt("index"));
            entity.setTips(jsonObject.getString("tips"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
